package client.comm.baoding.ui

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import client.comm.commlib.comm_ui.draw.SpacePblGridItemDecoration
import client.comm.commlib.toast.toast
import client.comm.commlib.widget.EmptyLayout
import client.comm.baoding.R
import client.comm.baoding.adapter.SearchRetAdapter
import client.comm.baoding.api.bean.SeartchRet
import client.comm.baoding.databinding.ActivitySearchretBinding
import client.comm.baoding.ui.vm.SearchRetModel
import client.comm.baoding.BaseMiddleActivity
import client.comm.commlib.base.PagerFooterAdapter
import client.comm.commlib.comm_ui.draw.SpaceGridItemDecoration
import client.comm.commlib.network.data.PagingJsonResult
import kotlinx.coroutines.flow.collect

class SearchRetActivity : BaseMiddleActivity<SearchRetModel, ActivitySearchretBinding>() {
    override fun getLayout(): Int {
        return R.layout.activity_searchret
    }

    val goodsAdapter: SearchRetAdapter by lazy {
        SearchRetAdapter(this, mImgLoader).apply {
            refreshLoading = {
                if (itemCount == 0) {
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_LOADING
                }
            }
            refreshNotLoading = {

                if (itemCount == 0) {
                    binding.emptyLayout.errorType = EmptyLayout.NODATA
                } else {
                    binding.emptyLayout.visibility = View.GONE
                }

            }
            refreshError = {
                if (itemCount == 0)
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
            }
        }
    }

    val typePopu: PopupWindow by lazy {
        val pp = PopupWindow(400, ViewGroup.LayoutParams.WRAP_CONTENT)
        val view = LayoutInflater.from(this).inflate(R.layout.layout_search_popu, null)

        view.findViewById<View>(R.id.goodsType).setOnClickListener {
            viewModel.searchType.value = "商品"
            typePopu.dismiss()
        }
        view.findViewById<View>(R.id.storeType).setOnClickListener {
            viewModel.searchType.value = "商店"
            typePopu.dismiss()
        }
        pp.isOutsideTouchable = true
        pp.setContentView(view)
        pp
    }

    override fun initView() {
        intent.getStringExtra("word")?.let {
            viewModel.wordVal.value = it
        }
        binding.event = this
        binding.vm = viewModel
        binding.recyclerView.adapter = goodsAdapter.withLoadStateFooter(PagerFooterAdapter())

        val gridLayoutManager =
            GridLayoutManager(this, 2)
        binding.recyclerView.addItemDecoration(
            SpaceGridItemDecoration(
                client.comm.commlib.dipToPx(resources!!, 10.0f).toInt()
            )
        )
        binding.recyclerView.layoutManager = gridLayoutManager

//        viewModel.searchType.observe(this, Observer {
//            binding.recyclerView.adapter = goodsAdapter
//            val gridLayoutManager =
//                StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
//
//            if (binding.recyclerView.itemDecorationCount > 0)
//                binding.recyclerView.removeItemDecorationAt(0)
//            binding.recyclerView.addItemDecoration(
//                SpacePblGridItemDecoration(
//                    client.comm.commlib.dipToPx(resources, 10.0f).toInt(),
//                    binding.recyclerView
//                )
//            )
//            binding.recyclerView.layoutManager = gridLayoutManager
//        })
    }

    override fun observerUI() {
        viewModel.sortMode.observe(this, Observer {
            when (it) {
                0 -> {
                    binding.imgOne.isSelected = false
                    binding.imgTwo.isSelected = false
                    binding.imgThree.isSelected = false
                    binding.imgFour.isSelected = false
                }
                1 -> {
                    binding.imgOne.isSelected = true
                    binding.imgTwo.isSelected = false
                    binding.imgThree.isSelected = false
                    binding.imgFour.isSelected = false
                }
                2 -> {
                    binding.imgOne.isSelected = false
                    binding.imgTwo.isSelected = true
                    binding.imgThree.isSelected = false
                    binding.imgFour.isSelected = false
                }
                3 -> {
                    binding.imgOne.isSelected = false
                    binding.imgTwo.isSelected = false
                    binding.imgThree.isSelected = true
                    binding.imgFour.isSelected = false
                }
                4 -> {
                    binding.imgOne.isSelected = false
                    binding.imgTwo.isSelected = false
                    binding.imgThree.isSelected = false
                    binding.imgFour.isSelected = true
                }
            }
            goSearch()
        })
    }

    override fun initViewModel(): SearchRetModel = createViewModel()

    fun showType(v: View) {
        if (typePopu.isShowing) {
            typePopu.dismiss()
        } else {
            typePopu.showAsDropDown(v, 0, 0)
        }
    }

    fun goSearch() {
        if (viewModel.wordVal.value.isNullOrEmpty()) {
            toast("请输入关键字")
            return
        }
        viewModel.page.value = 0
        viewModel.getData()

        lifecycleScope.launchWhenResumed {
            viewModel.pagingDataAuto {

                var priceStatus = ""
                var salesStatus = ""
                when (viewModel.currMode.value) {
                    1 -> {
                        if (viewModel.sortMode.value == 1) {
                            priceStatus = "0"
                        } else {
                            priceStatus = "1"
                        }
                    }
                    2 -> {
                        if (viewModel.sortMode.value == 3) {
                            salesStatus = "0"
                        } else {
                            salesStatus = "1"
                        }
                    }
                }
                val ret = viewModel.server.searchRet(
                    it, viewModel.wordVal.value!!,
                    priceStatus,
                    salesStatus
                )

                PagingJsonResult(
                    list = ret.body()?.data?.goods_list,
                    code = ret.body()?.code,
                    message = ret.body()?.message,
                    errorStr = ret.errorBody()?.string()
                )
            }.collect {
                goodsAdapter.submitData(it)
            }
        }
    }

    fun tabClick(index: Int) {
        when (index) {
            0 -> {
                viewModel.sortMode.value = 0
            }
            1 -> {
                if (viewModel.currMode.value == 1) {
                    viewModel.sortMode.value = if (viewModel.sortMode.value == 1) 2 else 1

                } else {
                    viewModel.sortMode.value = 1
                }
            }
            2 -> {
                if (viewModel.currMode.value == 2) {
                    viewModel.sortMode.value = if (viewModel.sortMode.value == 4) 3 else 4
                } else {
                    viewModel.sortMode.value = 3
                }
            }

        }
        viewModel.currMode.value = index
        goodsAdapter.refresh()
    }
}